package LearnAlgorithm.e_多维数组and矩阵;

/*
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
 */
public class a二维数组顺时针打印 {
	public static void main(String[] args) {
		int[][] matrix = new int[][] {
			{1,2,3,4},
			{5,6,7,8},
			{9,10,11,12},
			{13,14,15,16},
		};
		
		printclockwise(matrix);//1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 
	}
	
	public static void printclockwise(int[][] matrix) {
		int leftUpRow = 0;
		int leftUpCol = 0;
		int rihgtDownRow = matrix.length - 1;
		int rihgtDownCol = matrix[0].length - 1;
		
		while (leftUpRow <= rihgtDownRow && leftUpCol <= rihgtDownCol) {//<=有等于是应对特殊情况只有一个元素的matrix
			int r = leftUpRow;
			int c = leftUpCol;
			while (c <= rihgtDownCol) {//打印上边
				System.out.print(matrix[r][c++] + " ");
			}
			//恢复c
			c = rihgtDownCol;
			//r下移+1；为了避免重复的打印右上角
			r++;
			while (r <= rihgtDownRow) {//打印右边
				System.out.print(matrix[r++][c] + " ");
			}
			//恢复r
			r = rihgtDownRow;
			//c左移-1；为了避免重复的打印右下角
			c--;
			while (c >= leftUpCol) {
				System.out.print(matrix[r][c--] + " ");
			}
			//恢复c
			c = leftUpCol;
			//r上移-1；为了避免重复的打印左下角
			r--;
			while (r >= leftUpRow + 1) {//这里重点+1；避免重复打印左上角
				System.out.print(matrix[r--][c] + " ");
			}
			//将边界缩小
			leftUpRow++;
			leftUpCol++;
			rihgtDownRow--;
			rihgtDownCol--;
		}
	}
}
